package com.yuncheng.system.userlock.service;

import com.yuncheng.system.orguser.entity.SysUser;
import com.yuncheng.system.orguser.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UserLoader
 *
 * @date 2023/5/10
 */
@Service
public class UserLoader {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysUserLockService sysUserLockService;

    public SysUser loadUserByPhone(String phone){
        SysUser sysUser = sysUserService.getUserByPhone(phone);
        if (sysUser == null){
            return loadUserByUsername(phone);
        }else {
            sysUserLockService.isUserLocked(sysUser);
        }

        return sysUser;
    }

    public SysUser loadUserByUsername(String username) {
        SysUser sysUser = sysUserService.getUserByName(username);
        if (null == sysUser) {
            // 按用户的realname查找
            List<SysUser> users = this.sysUserService.lambdaQuery().eq(SysUser::getRealname, username).list();
            if (null != users && 1 == users.size()) {
                //找到唯一的用户，设为当前登录用户
                sysUser = users.get(0);
                username = sysUser.getUsername();
            } else {
                // 按用户的社会信用代码查找
                users = this.sysUserService.lambdaQuery().eq(SysUser::getUserExt3, username).list();
                if (null != users && 1 == users.size()) {
                    //找到唯一的用户，设为当前登录用户
                    sysUser = users.get(0);
                    username = sysUser.getUsername();
                }
            }
        }
        sysUserLockService.isUserLocked(sysUser);

        return sysUser;
    }

}
